package com.heima.search.interceptor;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自媒体端拦截器
 */
@Slf4j
public class AppUserTokenInterceptor implements HandlerInterceptor {


    /**
     * 前置处理 得到header中的用户信息 并且存入到当前线程中
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取请求头中的用户信息
        String userId = request.getHeader("userId");

        if (userId != null) {
            //存入当前线程中
            ApUser apUser = new ApUser();
            apUser.setId(Integer.parseInt(userId));
            AppThreadLocalUtil.setUser(apUser);

            log.info("ApuserTokenFilter设置用户信息到threadlocal中...");
        }

        return true;
    }


    /**
     * postHandle抛出异常后就不会在执行了
     *
     * 清理线程中的数据
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
       //log.info("清理threadlocal...");
       // AppUserThreadLocalUtil.removeUser();
    }

    /**
     * afterCompletion抛出异常后依然会执行
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("清理threadlocal...");
        AppThreadLocalUtil.removeUser();
    }
}
